<template>
  <div class="page_root" id="root_index">
    <div class="warp">
      <div class="container-fluid">
        <el-row>
          <el-col :class="'home_user'" :span="8">
            <el-card>
              <div class="card info">
                <div class='UserInfo'>
                  <el-row>
                    <el-col :span="8"><img :src="$fullUrl($banseUrl, UserInfo.avatar)" alt=""></el-col>
                    <el-col :span="12">
                      <p>用户昵称：{{UserInfo.nickname || UserInfo.username }}</p>
                      <p>用户身份：{{user_group}}</p>
                    </el-col>
                  </el-row>
                  <div>
                    <el-button @click="router.push('/home/info')">修改资料</el-button>
                    <el-button @click="router.push('/home/password')">修改密码</el-button>
                    <el-button @click="sign_out_fun">退出</el-button>
                  </div>
                  <p class='logotime'>上次登录时间：{{formatDate(UserInfo.login_time)}}</p>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :class="'home_notiece'" :span="8">
            <el-card>
              <div class="statistics chart">
                <diyNotice></diyNotice>
              </div>
            </el-card>
          </el-col>
          <el-col :class="'home_overview'" v-if="user_group == '管理员'" :span="8">
            <el-card>
              <div class="statistics card">
                <el-row>
                  <el-col :span="4" v-for="(item, index) in dataScreen" :key="index">
                    <div class="sumList">
                      <p>{{ item.value }}</p>
                      <p>{{ item.label }}</p>
                      <p>
                        <el-icon>
                          <Position/>
                        </el-icon>
                      </p>
                    </div>
                  </el-col>
                </el-row>
              </div>
            </el-card>
          </el-col>
          <el-col :class="'home_menu'" :span="24">
            <el-card>
              <quickMenu/>
            </el-card>
          </el-col>
          <el-col :class="'home_calendar'" :span="8">
            <el-card>
              <div class="card chart">
                <el-calendar v-model="calendarValue"/>
                <el-button @click="addSchedule">新增日程</el-button>
              </div>
            </el-card>
          </el-col>
          <el-col :class="'home_charts home_collet'" v-if="user_group == '管理员'" :span="8">
            <el-card>
              <div class="card chart">
                <newLineChart class="chartsHeiht" :color="['#fff000']" v-if="line_obj_collect_num.values.length > 0"
                        idName="line_obj_collect_num" :timeout="0" :title="'收藏数统计'" :vm="line_obj_collect_num">
                </newLineChart>
                <div v-if="!line_obj_collect_num.values.length">
                  收藏数没有符合条件的数据
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :class="'home_charts home_visit'" v-if="user_group == '管理员'" :span="8">
            <el-card>
              <div class="card chart">
                <newBarChart2 class="chartsHeiht" v-if="bar_obj_hits_num.values.length > 0"
                    idName="bar_obj_hits_num" :timeout="0" :title="'总访问数统计'" :vm="bar_obj_hits_num">
                </newBarChart2>
                <div v-if="!bar_obj_hits_num.values.length">
                  总访问数没有符合条件的数据
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :class="'home_charts home_users_num'" v-if="user_group == '管理员'" :span="8">
            <el-card>
              <div class="card chart">
                <newLineChart class="chartsHeiht" :color="['#fff000']" v-if="list_users_sums.values.length > 0"
                    idName="list_users_sums" :timeout="0" :title="'用户总数统计'" :vm="list_users_sums">
                </newLineChart>
                <div v-if="!list_users_sums.values.length">
                  用户总数没有符合条件的数据
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :class="'home_charts home_users_state'" v-if="user_group == '管理员'" :span="8">
            <el-card>
              <div class="card chart">
                <doughnutChart class="chartsHeiht" v-if="list_users_state.length"
                    idName="list_users_state" :list="list_users_state" :title="'用户状态统计'">
                </doughnutChart>
                <div v-if="!list_users_state.length">
                  用户状态没有符合条件的数据
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :class="'home_charts home_comment'" v-if="user_group == '管理员'" :span="8">
            <el-card>
              <div class="card chart">
                <stackedHorizontalBarChart class="chartsHeiht" style="margin-top: 20px; height: 620px" v-if="bar_obj_comments.values.length > 0"
                    idName="bar_obj_comments" :vm="bar_obj_comments" :title="'评论数统计'">
                </stackedHorizontalBarChart>
                <div v-if="!bar_obj_comments.values.length">
                  评论数没有符合条件的数据
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :class="'home_charts home_praise'" v-if="user_group == '管理员'" :span="8">
            <el-card>
              <div class="card chart">
                <basicAreaChart class="chartsHeiht" v-if="line_obj_likes.values.length > 0"
                    idName="line_obj_likes" :vm="line_obj_likes" :title="'点赞数统计'">
                </basicAreaChart>
                <div v-if="!line_obj_likes.values.length">
                  点赞数没有符合条件的数据
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :class="'home_charts home_users_states'" v-if="user_group == '管理员'" :span="8">
            <el-card>
              <div class="card chart">
                <basicScatterChart class="chartsHeiht" v-if="bubble_user_status.values.available.length > 0"
                    idName="bubble_user_status" :vm="bubble_user_status" :title="'用户状态统计'">
                </basicScatterChart>
                <div v-if="!bubble_user_status.values.available.length">
                  用户状态没有符合条件的数据
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :class="'home_charts home_visit_num'" v-if="user_group == '管理员'" :span="8">
            <el-card>
              <div class="card chart">
                <radarChart class="chartsHeiht" v-if="radar_obj_hits_num.values.length > 0"
                    idName="radar_obj_hits_num" :title="'访问数统计'" :vm="radar_obj_hits_num">
                </radarChart>
                <div v-if="!radar_obj_hits_num.values.length">
                  访问数没有符合条件的数据
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :class="'home_charts home_cart_trade'" v-if="$check_figure('/order/table')" :span="8">
            <el-card>
              <div class="card chart">
                <el-date-picker
                    v-model="line_obj_shop_money.month"
                    range-separator="至"
                    align="right"
                    end-placeholder="结束日期"
                    start-placeholder="开始日期"
                    type="daterange"
                    format="YYYY-MM-DD"
                    @change="changeMonth($event, line_obj_shop_money)"
                >
                </el-date-picker>
                <p style="text-align: right">
                  总销售金额：{{ line_obj_shop_money.total }}
                </p>
                <newLineChart
                    class="chartsHeiht"
                    :color="['#fff000']"
                    v-if="line_obj_shop_money.values.length > 0"
                    idName="line_obj_shop_money"
                    :timeout="0"
                    :title="'商品销售金额统计'"
                    :vm="line_obj_shop_money"
                >
                </newLineChart>
              </div>
            </el-card>
          </el-col>
          <el-col :class="'home_charts home_cart_sales'" v-if="user_group == '管理员' || $check_figure('/order/table')" :span="8">
            <el-card>
              <div class="card chart">
                <el-date-picker
                    v-model="bar_obj_shop_num.month"
                    align="right"
                    end-placeholder="结束日期"
                    start-placeholder="开始日期"
                    type="daterange"
                    format="YYYY-MM-DD"
                    @change="changeMonth($event, bar_obj_shop_num)"
                >
                </el-date-picker>
                <p style="text-align: right">
                  总销售数量：{{ bar_obj_shop_num.total }}
                </p>
                <newBarChart
                    class="chartsHeiht"
                    v-if="bar_obj_shop_num.values.length > 0"
                    idName="bar_obj_shop_num"
                    :timeout="0"
                    :title="'商品销售数量统计'"
                    :vm="bar_obj_shop_num"
                >
                </newBarChart>
              </div>
            </el-card>
          </el-col>
            <el-col :class="'home_charts home_customize_charts'" v-if="$check_figure('/registered_user/table')" :span="8">
            <el-card>
              <div class="card chart">
                                                                            <pieChart class="chartsHeiht" v-if="list_registered_user.length" idName="list_registered_user" :list="list_registered_user" :title="'注册用户统计'"></pieChart>
                <div v-if="!list_registered_user.length">注册用户没有符合条件的数据</div>
                                                                                                                                                                                    </div>
          </el-card>
        </el-col>
              <el-col :class="'home_charts home_customize_charts'" v-if="$check_figure('/merchant_users/table')" :span="8">
            <el-card>
              <div class="card chart">
                      <newBarChart class="chartsHeiht" v-if="bar_obj_merchant_users.values.length > 0" idName="bar_obj_merchant_users" :vm="bar_obj_merchant_users" :title="'商家用户统计'">
                </newBarChart>
                <div v-if="!bar_obj_merchant_users.values.length">商家用户没有符合条件的数据</div>
                  </div>
          </el-card>
        </el-col>
                  <el-col :class="'home_charts home_customize_charts'" v-if="$check_figure('/customized_products/table')" :span="8">
            <el-card>
              <div class="card chart">
                      <stackedHorizontalBarChart class="chartsHeiht" style="margin-top: 20px; height: 620px" v-if="bar_obj_customized_products.values.length > 0"
                                            idName="bar_obj_customized_products" :vm="bar_obj_customized_products" :title="'定制商品统计'">
                </stackedHorizontalBarChart>
                <div v-if="!bar_obj_customized_products.values.length">定制商品没有符合条件的数据</div>
                  </div>
          </el-card>
        </el-col>
              <el-col :class="'home_charts home_customize_charts'" v-if="$check_figure('/i_want_to_customize_it/table')" :span="8">
            <el-card>
              <div class="card chart">
                      <gradientStackedAreaChart class="chartsHeiht" v-if="line_obj_i_want_to_customize_it.values.length > 0"
                        idName="line_obj_i_want_to_customize_it" :vm="line_obj_i_want_to_customize_it" :title="'我要定制统计'">
                </gradientStackedAreaChart>
                <div v-if="!line_obj_i_want_to_customize_it.values.length">我要定制没有符合条件的数据</div>
                  </div>
          </el-card>
        </el-col>
                      <el-col :class="'home_charts home_exam_subject'" v-if="user_group != '管理员' && !$check_option('/subject_exam/table', 'teacher') && $check_figure('/subject_exam/table')" :span="8">
            <el-card>
              <div class="card chart">
                <subjectExamCharts
                    class="chartsHeiht"
                    v-if="bar_obj_subject_exam.values.length > 0"
                    idName="line_obj_data_account_statistics"
                    :title="'用户考试科目数据统计'"
                    :vm="bar_obj_subject_exam"
                    @changeTab="get_url_subject_exam_list"
                >
                </subjectExamCharts>
                <div v-if="!bar_obj_subject_exam.values.length">
                  数据分析没有符合条件的数据
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :class="'home_charts home_exam_avgscore'" v-if="$check_figure('/subject_exam/table')" :span="8">
            <el-card>
              <div class="card chart">
                <subjectExamCharts
                    class="chartsHeiht"
                    v-if="bar_obj_subject_exam_avg.values.length > 0"
                    idName="line_obj_data_account_avg"
                    :title="'试卷平均分统计'"
                    :vm="bar_obj_subject_exam_avg"
                    avg
                    @changeTab="get_subject_average"
                >
                </subjectExamCharts>
                <div v-if="!bar_obj_subject_exam_avg.values.length">
                  数据分析没有符合条件的数据
                </div>
              </div>
            </el-card>
          </el-col>

          <el-col :class="'home_charts home_exam_score'" v-if="user_group == '管理员' || $check_figure('/subject_exam/table')" :span="8">
            <el-card>
              <div class="card chart">
                <subjectExamTable
                    class="chartsHeiht"
                    v-if="subject_name_list_num.length > 0"
                    :vm="subject_name_list_num"
                ></subjectExamTable>
                <div v-if="!subject_name_list_num.length">
                  数据总览没有符合条件的数据
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :class="'home_charts home_operatelog'" :span="8">
            <el-card>
              <div class="card chart">
                <diyLog></diyLog>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>
<script setup>
  import moment from "moment";
  import { $post, $get } from "@/api/Api.js";
  import {ref, onMounted, computed} from "vue";
  import {
    formatDate,
          $check_option,
          $check_figure,
          $toTime,
          $fullUrl,
          $banseUrl,
  } from "@/utils/utils.js";
  import quickMenu from "@/components/diy/quick_menu.vue";
  import diyLog from "@/components/diy/diy_log.vue";
  import diyNotice from "@/components/diy/diy_notice.vue";
  import radarChart from "@/components/charts/radar_chart.vue";
  import pieChart from "@/components/charts/pie_chart.vue";
  import newBarChart from "@/components/charts/new_bar_chart.vue";
  import newBarChart2 from "@/components/charts/new_bar_chart2.vue";
  import newLineChart from "@/components/charts/new_line_chart.vue";
  import basicAreaChart from "@/components/charts/basic_area_chart.vue";
  import basicScatterChart from "@/components/charts/basic_scatter_chart.vue";
  import doughnutChart from "@/components/charts/doughnut_chart.vue";
  import stackedHorizontalBarChart from "@/components/charts/stacked_horizontal_bar_chart.vue";
  import gradientStackedAreaChart from "@/components/charts/gradient_stacked_area_chart.vue";
  import subjectExamCharts from "@/components/charts/subject_exam_charts.vue";
  import subjectExamTable from "@/components/charts/subject_exam_table.vue";
  import {useStore} from "vuex";
  import {useRouter} from "vue-router";
  import storageHelper from "@/libs/StorageHelper";

  let UserInfo = storageHelper.getUserInfo();
  let user_group = storageHelper.getGroupValue();
  let router = useRouter();
  let store = useStore();
  let recognitionHeight = ref("830px");
  let recognitionUrl = ref(
      "https://www.faceplusplus.com.cn/license-plate-recognition/"
  );
  let sign_out = (payload) => store.commit("userStoreModule/sign_out", payload);
  // 数据预览模块
  let dataScreen = ref([])
  // 固定预览数据
  let sumList = ref([
    {
      label: "用户总数",
      value: "111",
      icon: "Position",
      field: "user",
    },
    {
      label: "正常账号",
      value: "111",
      icon: "Position",
      field: "normal_user",
    },
    {
      label: "冻结账号",
      value: "111",
      icon: "Position",
      field: "freeze_user",
    },
    {
      label: "管理员",
      value: "111",
      icon: "Position",
      field: "admin_user",
    },
      {
      label: "注册用户",
      value: "111",
      icon: "Position",
      field: "registered_user",
    },
        {
      label: "商家用户",
      value: "111",
      icon: "Position",
      field: "merchant_users",
    },
                        {
      label: "访问总数",
      value: "111",
      icon: "Position",
      field: "hits",
    },
    {
      label: "轮播图数",
      value: "111",
      icon: "Position",
      field: "slides",
    },
    {
      label: "收藏数",
      value: "111",
      icon: "Position",
      field: "collect",
    },
    {
      label: "评论数",
      value: "111",
      icon: "Position",
      field: "user",
    },
    {
      label: "点赞数",
      value: "111",
      icon: "Position",
      field: "praise",
    },
    {
      label: "公告数",
      value: "111",
      icon: "Position",
      field: "notice",
    },
  ]);
  // 用户状态--环形图
  let list_users_state = ref([]);
  //当年 1-6月最大，最小日期
  let monthDateList = ref([]);
  let month_list = ref(["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"]);
  let now_month = new Date().getMonth() + 1;
  // 用户总数
  let list_users_sums = ref({
    type: "usersSums",
    names: ["用户总数"],
    xAxis: month_list.value.slice(now_month -6, now_month).length>=6?month_list.value.slice(now_month -6, now_month):month_list.value.slice(month_list.value.length-(6-(month_list.value.slice(0, now_month).length)),month_list.value.length).concat(month_list.value.slice(0, now_month)),
    values: [],
    month: [],
    loading: false,
    total: 0,
  });
  // 评论数	1-6月
  let bar_obj_comments = ref({
    names: ["评论数"],
    xAxis: month_list.value.slice(now_month -6, now_month).length>=6?month_list.value.slice(now_month -6, now_month):month_list.value.slice(month_list.value.length-(6-(month_list.value.slice(0, now_month).length)),month_list.value.length).concat(month_list.value.slice(0, now_month)),
    values: [],
  });
  // 收藏数	1-6月
  let line_obj_collect_num = ref({
    type: "money",
    names: ["收藏数"],
    xAxis: month_list.value.slice(now_month -6, now_month).length>=6?month_list.value.slice(now_month -6, now_month):month_list.value.slice(month_list.value.length-(6-(month_list.value.slice(0, now_month).length)),month_list.value.length).concat(month_list.value.slice(0, now_month)),
    values: [],
    month: [],
    loading: false,
    total: 0,
  });

  // 总访问数	1-6月
  let bar_obj_hits_num = ref({
    type: "num",
    names: ["总访问数"],
    xAxis: month_list.value.slice(now_month -6, now_month).length>=6?month_list.value.slice(now_month -6, now_month):month_list.value.slice(month_list.value.length-(6-(month_list.value.slice(0, now_month).length)),month_list.value.length).concat(month_list.value.slice(0, now_month)),
    values: [],
    month: [],
    loading: false,
    total: 0,
  });
  // 访问数	1-6月	雷达图
  let radar_obj_hits_num = ref({
    names: ["访问数"],
    indicator: (month_list.value.slice(now_month -6, now_month).length>=6?month_list.value.slice(now_month -6, now_month):month_list.value.slice(month_list.value.length-(6-(month_list.value.slice(0, now_month).length)),month_list.value.length).concat(month_list.value.slice(0, now_month))).map(
            (item) => {
              return {
                name: item,
                value: 10,
              };
            }
    ),
    values: [],
  });
  // 点赞数	1-6月
  let line_obj_likes = ref({
    names: ["点赞数"],
    xAxis: month_list.value.slice(now_month -6, now_month).length>=6?month_list.value.slice(now_month -6, now_month):month_list.value.slice(month_list.value.length-(6-(month_list.value.slice(0, now_month).length)),month_list.value.length).concat(month_list.value.slice(0, now_month)),
    values: [],
  });
  // 用户状态--散点图  1-6月	 // 获取通用户状态 (1可用|2异常|3已冻结|4已注销)
  let bubble_user_status = ref({
    names: ["可用账户", "冻结账户"],
    xAxis: month_list.value.slice(now_month -6, now_month).length>=6?month_list.value.slice(now_month -6, now_month):month_list.value.slice(month_list.value.length-(6-(month_list.value.slice(0, now_month).length)),month_list.value.length).concat(month_list.value.slice(0, now_month)),
    values: {
      available: [],
      freeze: [],
    },
  });
  let line_obj_shop_money = ref({
    type: "money",
    names: ["销售金额"],
    xAxis: [],
    values: [],
    month: [],
    loading: false,
    total: 0,
  });

  let bar_obj_shop_num = ref({
    type: "num",
    names: ["销售数量"],
    xAxis: [],
    values: [],
    month: [],
    loading: false,
    total: 0,
  });
  let subject_name_list_num = ref([]);
  let bar_obj_subject_exam = ref({
    names: [],
    xAxis: [],
    values: [],
    tabs: [],
  });
  let bar_obj_subject_exam_avg = ref({
    names: [],
    xAxis: [],
    values: [],
    tabs: [],
  });
    let list_registered_user = ref([]);
      let bar_obj_merchant_users = ref({
    names: [],
    xAxis: [],
    values: [],
  });
              let bar_obj_customized_products = ref({
    names: [],
    xAxis: [],
    values: [],
  });
      let line_obj_i_want_to_customize_it = ref({
    names: [],
    xAxis: [],
    values: [],
  });
                        // 动态获取自定义模块
  const auth = computed(() => {
  let tables = JSON.parse(window.localStorage.getItem("set_auth"));
  let lt = [];
  let site_list = [];
  let IconArr = ["Edit", "Document", "Menu", "Location", "Setting", "Search"];
              site_list.push("i_want_to_customize_it")
              let list = [
    "exam",
    "article",
    "article_type",
    "comment",
,
    "goods",
    "order",
      "logistics_delivery",
      "forum",
    "forum_type",
    "notice",
    "message",
    "subject",
    "exam_question_database",
    "subject_exam",
    "user_answer_wrong",
  ];
                        list.push("fresh_products");
                                                            list.push("registered_user");
        list.push("merchant_users");
                        for (let i = 0; i < tables.length; i++) {
      let o = tables[i];
      if (o.path.indexOf("/table") !== -1) {
        if (list.indexOf(o.table_name) === -1) {
          o.has_add = site_list.indexOf(o.table_name) === -1;
          o.Icon = IconArr[parseInt(Math.random() * IconArr.length)];
          lt.push({
            label: o.mod_name,
            value: "111",
            icon: o.Icon,
            field: o.table_name,
          });
        }
      }
    }

    return lt;
  });
  let calendarValue = ref(new Date());
  //  新增日程
  const addSchedule = (date) => {
    ElMessageBox.prompt("请输入日程内容:", "新增日程", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
    })
        .then(({value}) => {
          // 这里可以将日程内容和日期发送到服务器进行保存
          console.log("新日程:", value, "日期:", calendarValue.value);
          ElMessageBox.alert(
              `日程 "${value}" 已添加到 ${calendarValue.value.toDateString()}.`
          );
        })
        .catch(() => {
          // 取消添加日程
        });
  };
  // 退出登录
  let sign_out_fun = () => {
    sign_out([]);
          $get("/api/user/quit").then((res) => {
      store.commit("web/set_auth", []);
      sessionStorage.clear();
      localStorage.clear();
      router.push("/");
    });
  };
  // 数据预览模块
  let get_list_count = () => {
    // 合并固定数据预览+自定义模块的
    dataScreen.value = [...sumList.value, ...auth.value]
    ///api/user/count?state=3(1可用|2异常|3已冻结|4已注销) --/api/user/count?user_group=管理员
    for (let i = 0; i < dataScreen.value.length; i++) {
      let url;
      let obj = dataScreen.value[i]
      if (obj.field != 'normal_user' && obj.field !== 'freeze_user' && obj.field !== 'admin_user') {
        url = `/api/${obj.field}/count`
              $get(url).then((json) => {
          if (json.result !== null) {
            obj.value = json.result;
          }
        });
      } else {
        // 正常账户，冻结账户数据获取
        let data = {}
        url = `/api/user/count`
        if (obj.field === 'normal_user') {
          data = {
            state: 1
          }
        } else if (obj.field === 'freeze_user') {
          data = {
            state: 3
          }
        } else {
          data = {
            user_group: '管理员'
          }

        }
        $get(url, data).then((json) => {
          if (json.result !== null) {
            obj.value = json.result;
          }
        });
      }
    }
  };

  // 获取当年1-6月最大，最小日期
  let getMonthDateList = () => {
    let monthList = month_list.value.slice(now_month -6, now_month).length>=6?month_list.value.slice(now_month -6, now_month):month_list.value.slice(month_list.value.length-(6-(month_list.value.slice(0, now_month).length)),month_list.value.length).concat(month_list.value.slice(0, now_month));
    monthDateList.value = [];
    if (now_month>=5){
      let index = 0;
      const currentYear = new Date().getFullYear();
      for (let i = (now_month-5); i <= now_month; i++) {
        let maxDay = new Date(currentYear, i, 0).getDate();
        monthDateList.value.push({
          name: index,
          month: monthList[index],
          create_time_min: currentYear+'-'+i.toString().padStart(2, "0")+'-01 00:00:00',
          create_time_max: currentYear+'-'+i.toString().padStart(2, "0")+'-'+maxDay+' 23:59:59',
        });
        index++;
      }
    }else {
      const currentYear = new Date().getFullYear();
      const lastYear = currentYear - 1;
      let index = 0;
      console.log(lastYear)
      //循环去年
      for (let i = 12-(6-(now_month+1)); i <= 12; i++) {
        let maxDay = new Date(lastYear, i, 0).getDate();
        monthDateList.value.push({
          name: index,
          month: monthList[index],
          create_time_min: lastYear+'-'+i.toString().padStart(2, "0")+'-01 00:00:00',
          create_time_max: lastYear+'-'+i.toString().padStart(2, "0")+'-'+maxDay+' 23:59:59',
        })
        index++;
      }
      //循环今年
      for (let i = 1; i <= now_month; i++) {
        let maxDay = new Date(currentYear, i, 0).getDate();
        monthDateList.value.push({
          name: index,
          month: monthList[index],
          create_time_min: currentYear+'-'+i.toString().padStart(2, "0")+'-01 00:00:00',
          create_time_max: currentYear+'-'+i.toString().padStart(2, "0")+'-'+maxDay+' 23:59:59',
        })
        index++;
      }
    }
    // monthDateList.value.sort((a, b) => a.name - b.name);
  };
  // 获取通用户总数1-6月
  let get_list_users_sums = async () => {
    for (let i = 0; i < monthDateList.value.length; i++) {
      let data = {
        create_time_min: monthDateList.value[i].create_time_min,
        create_time_max: monthDateList.value[i].create_time_max,
      };
            $get("/api/user/count", data).then((json) => {
        if (json.result !== null) {
          list_users_sums.value.values[i] = json.result;
        }
      });
    }
  };
  // 总访问数 1-6月
  let get_list_hits_sums = async () => {
    for (let i = 0; i < monthDateList.value.length; i++) {
      let data = {
        create_time_min: monthDateList.value[i].create_time_min,
        create_time_max: monthDateList.value[i].create_time_max,
      };
            $get("/api/hits/count", data).then((json) => {
        if (json.result !== null) {
          bar_obj_hits_num.value.values[i] = json.result;
          radar_obj_hits_num.value.values[i] = json.result;
        }
      });
    }
  };
  // 收藏数 1-6月
  let get_list_collect_sums = async () => {
    for (let i = 0; i < monthDateList.value.length; i++) {
      let data = {
        create_time_min: monthDateList.value[i].create_time_min,
        create_time_max: monthDateList.value[i].create_time_max,
      };
      $get("/api/collect/count", data).then((json) => {
        if (json.result !== null) {
          line_obj_collect_num.value.values[i] = json.result;
        }
      });
    }
  };
  // 点赞数	1-6月
  let get_list_praise_sums = async () => {
    for (let i = 0; i < monthDateList.value.length; i++) {
      let data = {
        create_time_min: monthDateList.value[i].create_time_min,
        create_time_max: monthDateList.value[i].create_time_max,
      };
            $get("/api/praise/count", data).then((json) => {
        if (json.result !== null) {
          line_obj_likes.value.values[i] = json.result;
        }
      });
    }
  };

  // 用户状态--散点图  1-6月
  let get_bubble_user_status = async () => {
    for (let i = 0; i < monthDateList.value.length; i++) {
      let data = {
        groupby:'state',
        create_time_min: monthDateList.value[i].create_time_min,
        create_time_max: monthDateList.value[i].create_time_max,
      };
      $get("/api/user/list_group", data).then((json) => {
        if (json.result !== null) {
          if (json.result.list[0] && json.result.list[0][0]) {
            bubble_user_status.value.values.available[i] = [monthDateList.value[i].name, json.result.list[0][0]];
          } else {
            bubble_user_status.value.values.available[i] = [monthDateList.value[i].name, 0];
          }
          if (json.result.list[0] && json.result.list[0][1]) {
            bubble_user_status.value.values.freeze[i] = [monthDateList.value[i].name, json.result.list[0][1]];
          } else {
            bubble_user_status.value.values.freeze[i] = [monthDateList.value[i].name, 0];
          }
        }
      });
    }
  };
  // 评论数	1-6月
  let get_list_comments_sums = async () => {
    for (let i = 0; i < monthDateList.value.length; i++) {
      let data = {
        create_time_min: monthDateList.value[i].create_time_min,
        create_time_max: monthDateList.value[i].create_time_max,
      };
            $get("/api/comment/count", data).then((json) => {
        if (json.result !== null) {
          bar_obj_comments.value.values[i] = json.result;
        }
      });
    }
  };
  // 获取通用户状态 (1可用|2异常|3已冻结|4已注销)
  let get_list_users_state = () => {
    let data = {
      groupby: "state",
    };
    $get("/api/user/list_group", data).then((json) => {
      if (json.result) {
        var list = json.result.list;
        let arr = [];
        for (let i = 0;i<list.length;i++) {
          let obj = {};
          switch (list[i]['state'].toString()) {
            case "1":
              obj = {value: list[i]['count'], name: "可用账户"};
              break;
            case "2":
              obj = {value: list[i]['count'], name: "异常账户"};
              break;
            case "3":
              obj = {value: list[i]['count'], name: "已冻结账户"};
              break;
            case "4":
              obj = {value: list[i]['count'], name: "已注销账户"};
              break;
            default:
              break;
          }
          arr.push(obj);
        }
        list_users_state.value = arr;
      }
    });
  };
  let get_nickname = async (list, flag) => {
    if (flag) {
      for (let i = 0; i < list.length; i++) {
        await $get(`/api/user/get_obj?user_id=` + list[i]).then((json) => {
          if (json.result) {
            list[i] = json.result.obj.nickname;
          }
        });
      }
    } else {
      for (let i = 0; i < list.length; i++) {
        await $get(`/api/user/get_obj?user_id=` + list[i].name).then((json) => {
          if (json.result) {
            list[i].name = json.result.obj.nickname;
          }
        });
      }
    }
  };
  let get_url_subject_list = async () => {
    const result = await $get("/api/subject/get_list");
    for (let i = 0; i < result.result.list.length; i++) {
      bar_obj_subject_exam.value.tabs.push(result.result.list[i].name);
      bar_obj_subject_exam_avg.value.tabs.push(result.result.list[i].name);
    }
    await get_url_subject_exam_list(bar_obj_subject_exam.value.tabs[0]);
    await get_subject_average(bar_obj_subject_exam.value.tabs[0]);
    bar_obj_subject_exam.value.names = [bar_obj_subject_exam.value.tabs[0]];
  };

  let get_url_subject_exam_list = async (e) => {
    let url = "/api/subject_exam/get_list?subject_name=" + e;
    if (
        user_group !== "管理员" &&
                $check_option("/subject_exam/table", "teacher")
    ) {
      url =
          "/api/subject_exam/get_list?subject_name=" +
          e +
          "&user_id=" +
          UserInfo.user_id;
    }
    const json = await $get(url);
    const allResult = [];
    bar_obj_subject_exam.value.xAxis = [];
    for (let j = 0; j < json.result.list.length; j++) {
      bar_obj_subject_exam.value.xAxis.push(json.result.list[j].name);
      let params = {
        exam_id: json.result.list[j].exam_id,
        user_id: UserInfo.user_id,
      };
      if (
          user_group !== "管理员" &&
                  $check_option("/subject_exam/table", "teacher")
      ) {
        params = {
          exam_id: json.result.list[j].exam_id,
        };
      }
      const value = await $get("/api/subject_user_answer/get_list", params);
      if (value.result.list.length <= 0) {
        allResult.push([]);
      } else {
        for (let k = 0; k < value.result.list.length; k++) {
          allResult.push([value.result.list[k].score]);
        }
      }
    }
    bar_obj_subject_exam.value.values = allResult;
    bar_obj_subject_exam.value.names = [e];
  };

  let find_subject_item = (arr, key, val) => {
    for (let i = 0; i < arr.length; i++) {
      if (arr[i][key] == val) {
        return i;
      }
    }
    return -1;
  };
  let get_subject_average = async (e) => {
    const subject_name_list = [];
    let url = "/api/subject_exam/get_list";
    if (
        user_group !== "管理员" &&
                $check_option("/subject_exam/table", "teacher")
    ) {
      url = "/api/subject_exam/get_list?user_id=" + UserInfo.user_id;
    }
    const json = await $get(url);
    for (let i = 0; i < json.result.list.length; i++) {
      const value = json.result.list[i].subject_name;
      const index = find_subject_item(subject_name_list, "name", value);
      if (index === -1) {
        subject_name_list.push({
          name: json.result.list[i].subject_name,
          exam: [json.result.list[i].exam_id],
          examNames: [json.result.list[i].name],
          score: [],
          userList: [],
          min: [],
          max: [],
          avg: [],
        });
      } else {
        subject_name_list[index].exam.push(json.result.list[i].exam_id);
        subject_name_list[index].examNames.push(json.result.list[i].name);
      }
    }

    const result = await $get("/api/subject_user_answer/get_list");
    for (let i = 0; i < result.result.list.length; i++) {
      for (let j = 0; j < subject_name_list.length; j++) {
        const exam_index = subject_name_list[j].exam.indexOf(
            result.result.list[i].exam_id
        );
        if (exam_index > -1) {
          if (!subject_name_list[j].score[exam_index]) {
            subject_name_list[j].score[exam_index] = [];
            subject_name_list[j].userList[exam_index] = [];
          }
          const user_index = subject_name_list[j].userList[exam_index].indexOf(
              result.result.list[i].user_id
          );
          if (user_index === -1) {
            subject_name_list[j].userList[exam_index].push(
                result.result.list[i].user_id
            );
          }
          subject_name_list[j].score[exam_index].push(
              result.result.list[i].score
          );
        }
      }
    }

    bar_obj_subject_exam_avg.value.names = ["平均分", "最高分", "最低分"];
    bar_obj_subject_exam_avg.value.values = [[], [], []];

    for (let i = 0; i < subject_name_list.length; i++) {
      for (let j = 0; j < subject_name_list[i].score.length; j++) {
        const max = Math.max.apply(Math, subject_name_list[i].score[j]);
        const min = Math.min.apply(Math, subject_name_list[i].score[j]);
        const avg =
            subject_name_list[i].score[j].reduce(function (a, b) {
              return a + b;
            }) / subject_name_list[i].score[j].length;
        if (subject_name_list[i].name === e) {
          bar_obj_subject_exam_avg.value.xAxis = subject_name_list[i].examNames;
          bar_obj_subject_exam_avg.value.values[0].push(avg);
          bar_obj_subject_exam_avg.value.values[1].push(max);
          bar_obj_subject_exam_avg.value.values[2].push(min);
        }
        subject_name_list[i].avg.push(avg);
        subject_name_list[i].max.push(max);
        subject_name_list[i].min.push(min);
      }
    }
    subject_name_list_num.value = subject_name_list;
  };
  let getDateBetween = (start, end) => {
    var result = [];
    //使用传入参数的时间
    var startTime = new Date(start);
    var endTime = new Date(end);
    while (endTime - startTime >= 0) {
      let year = startTime.getFullYear();
      let month = startTime.getMonth();
      month = month < 9 ? "0" + (month + 1) : month + 1;
      let day =
          startTime.getDate().toString().length === 1
              ? "0" + startTime.getDate()
              : startTime.getDate();
      //加入数组
      result.push(year + "-" + month + "-" + day);
      //更新日期
      startTime.setDate(startTime.getDate() + 1);
    }
    return result;
  };
  // 获取指定日期的数据
  let get_order_month_some_price = async (date, o) => {
    const now = new Date();
    const nowYear = now.getFullYear();
    const nowMonth = now.getMonth() + 1;
    const nowDate = now.getDate();
    let days = [];
    if (date) {
      days = getDateBetween(date[0], date[1]);
    } else {
      o.month[0] = new Date(nowYear, nowMonth - 1, 1, 0, 0, 0);
      o.month[1] = new Date(nowYear, nowMonth - 1, nowDate, 23, 59, 59);
      days = getDateBetween(o.month[0], o.month[1]);
    }

    o.xAxis = [];
    o.values = [];
    o.loading = true;
    let list = {
      result: [],
      total: 0,
    };
    let field = o.type === "money" ? "price_count" : "num";
    for (let i = 0; i < days.length; i++) {
      const t = new Date(days[i]);
      const time = t.getFullYear() + "-" + (t.getMonth() + 1) + "-" + t.getDate();
      o.xAxis.push(t.getMonth() + 1 + "-" + t.getDate());
      await get_order_sum_price_sub(list, time, i, field);
    }
    o.loading = false;
    o.values = list.result;
    o.total = list.total;
  };
  // 获取某一天的销售数量
  let get_order_sum_price_sub = async (list, date, index, field) => {
    let time = $toTime(date, "YYYY-MM-DD");
    var $where = "";
    if (user_group != "管理员") $where = "&merchant_id=" + UserInfo.user_id;
    const json = await $get(
        `/api/order/sum?field=${field}&create_time_min=${time} 00:00:00&create_time_max=${time} 23:59:59&state=已付款` +
                $where
    );
    list.result[index] = [];
    if (json.result) {
      list.total += json.result;
      list.result[index].push(json.result);
    } else {
      list.result[index].push(0);
    }
  };
  // 选择日期
  let changeMonth = (e, o) => {
    get_order_month_some_price(e, o);
  };
                                      // 获取注册用户统计图数据
  let get_list_registered_user = async () => {
        let data = {
          groupby: "user_gender"
        };
                  let flag = false;
                        $get("/api/registered_user/list_group", data).then((json) => {
          if (json.result) {
            var list = json.result.list;
            list_registered_user.value = list.map((o) => {
              return {
                              name: o[1],
                              value: o[0],
              };
            });
            if (flag) {
              get_nickname(list_registered_user.value, false);
            }
          }
        });
      };
                                                                                                // 获取商家用户统计图
  let get_list_merchant_users = async () => {
    let name_list = [];
    let query_str = "";
                  let group_by_value = "merchant_name";
                  let flag = false;
                          let date_flag = "其他"
                                                                                            name_list.push("注册资金");
        query_str = query_str+"registered_capital"+","
                              name_list.push("公司人数");
        query_str = query_str+"number_of_employees"+","
              bar_obj_merchant_users.value.names = name_list;
    query_str = query_str.substr(0,query_str.length-1);
    let data = {
      field: query_str,
      groupby: group_by_value,
    };
        await $get("/api/merchant_users/bar_group", data).then((json) => {
      if (json.result) {
        let xAxis = [];
        let values = [];
        json.result.list.map((o) => {
          if (date_flag === "日期") {
            xAxis.push($toTime(o[0], "YYYY-MM-DD"));
          } else if (date_flag === "时间") {
            xAxis.push($toTime(o[0], "hh:mm:ss"));
          } else if (date_flag === "日长") {
            xAxis.push($toTime(o[0], "YYYY-MM-DD HH:mm:ss"));
          } else {
            xAxis.push(o[0]);
          }
          values.push(o.splice(1));
        });
        bar_obj_merchant_users.value.xAxis = xAxis;
        bar_obj_merchant_users.value.values = values;
      }
      if (flag) {
        get_nickname(bar_obj_merchant_users.value.xAxis, true);
      }
    });
  };
              // 获取定制商品统计图
  let get_list_customized_products = async () => {
    let name_list = [];
    let query_str = "";
                                                  let group_by_value = "classification_name";
                  let flag = false;
                          let date_flag = "其他"
                                                                            name_list.push("定制库存");
        query_str = query_str+"customized_inventory"+","
                                                                                                                              name_list.push("定制价格");
        query_str = query_str+"customized_pricing"+","
                                              bar_obj_customized_products.value.names = name_list;
    query_str = query_str.substr(0,query_str.length-1);
    let data = {
      field: query_str,
      groupby: group_by_value,
    };
          let user_id = UserInfo.user_id;
      if (user_group!='管理员'){
                  let sqlwhere = "(";
                                                                                                                                                                                              if (user_group=="商家用户"){
                sqlwhere+= "merchant_users = " + user_id + " or ";
              }
                                                                                                                                                                                          if (sqlwhere.length>1){
            sqlwhere = sqlwhere.substr(0,sqlwhere.length-4);
            sqlwhere += ")";
            data.sqlwhere = sqlwhere;
          }
              }
        await $get("/api/customized_products/bar_group", data).then((json) => {
      if (json.result) {
        let xAxis = [];
        let values = [];
        json.result.list.map((o) => {
          if (date_flag === "日期") {
            xAxis.push($toTime(o[0], "YYYY-MM-DD"));
          } else if (date_flag === "时间") {
            xAxis.push($toTime(o[0], "hh:mm:ss"));
          } else if (date_flag === "日长") {
            xAxis.push($toTime(o[0], "YYYY-MM-DD HH:mm:ss"));
          } else {
            xAxis.push(o[0]);
          }
          values.push(o.splice(1));
        });
        bar_obj_customized_products.value.xAxis = xAxis;
        bar_obj_customized_products.value.values = values;
      }
      if (flag) {
        get_nickname(bar_obj_customized_products.value.xAxis, true);
      }
    });
  };
      // 获取我要定制统计图数据
  let get_list_i_want_to_customize_it = async () => {
                                      let group_by_value = "product_name";
        let data = {
          groupby: group_by_value,
        };
                  let flag = false;
                          let user_id = UserInfo.user_id;
          if (user_group!='管理员'){
                          let sqlwhere = "(";
                                                                                                                                                                                                                                    if (user_group=="商家用户"){
                    sqlwhere+= "merchant_users = " + user_id + " or ";
                  }
                                                                                                                                                                                        if (user_group=="注册用户"){
                    sqlwhere+= "customized_users = " + user_id + " or ";
                  }
                                                                                                                                                                                                                                if (sqlwhere.length>1){
                sqlwhere = sqlwhere.substr(0,sqlwhere.length-4);
                sqlwhere += ")";
                data.sqlwhere = sqlwhere;
              }
                      }
                await $get("/api/i_want_to_customize_it/get_list", data).then((json) => {
          if (json.result) {
            let list = json.result.list;
            let name_list = [];
            for (let i = 0; i < list.length; i++) {
              name_list.push(list[i].product_name);
            }
            line_obj_i_want_to_customize_it.value.names = name_list;
            get_list_i_want_to_customize_it_sub("product_name", flag);
          }
        });
                                                                                                                                                                  };
  let  get_list_i_want_to_customize_it_sub = async (v1, names_flag) => {
                                                                                                                                                              let data = {
          groupby: "delivery_date",
        };
                  let flag = false;
                          let user_id = UserInfo.user_id;
          if (user_group!='管理员'){
                          let sqlwhere = "(";
                                                                                                                                                                                                                                    if (user_group=="商家用户"){
                    sqlwhere+= "merchant_users = " + user_id + " or ";
                  }
                                                                                                                                                                                        if (user_group=="注册用户"){
                    sqlwhere+= "customized_users = " + user_id + " or ";
                  }
                                                                                                                                                                                                                                if (sqlwhere.length>1){
                sqlwhere = sqlwhere.substr(0,sqlwhere.length-4);
                sqlwhere += ")";
                data.sqlwhere = sqlwhere;
              }
                      }
                await $get("/api/i_want_to_customize_it/get_list", data).then((json) => {
          if (json.result) {
            let list = json.result.list;
            let xAxis_list = [];
            for (let i = 0; i < list.length; i++) {
                              xAxis_list.push($toTime(list[i].delivery_date ,"YYYY-MM-DD"));
                          }
            line_obj_i_want_to_customize_it.value.xAxis = xAxis_list;
            get_list_i_want_to_customize_it_sub_sub(v1,"delivery_date",names_flag,flag);
          }
        });
                                          };
  let get_list_i_want_to_customize_it_sub_sub = async (v1,v2,names_flag,xAxis_flag) => {
                                                                                                                      let data_str = "{\""+v1+"\":\"\",\""+v2+"\":\"\"}";
        let data = JSON.parse(data_str);
                  let user_id = UserInfo.user_id;
          if (user_group!='管理员'){
                          let sqlwhere = "(";
                                                                                                                                                                                                                                    if (user_group=="商家用户"){
                    sqlwhere+= "merchant_users = " + user_id + " or ";
                  }
                                                                                                                                                                                        if (user_group=="注册用户"){
                    sqlwhere+= "customized_users = " + user_id + " or ";
                  }
                                                                                                                                                                                                                                if (sqlwhere.length>1){
                sqlwhere = sqlwhere.substr(0,sqlwhere.length-4);
                sqlwhere += ")";
                data.sqlwhere = sqlwhere;
              }
                      }
                data["field"] = "total_price";
        for (let i = 0; i < line_obj_i_want_to_customize_it.value.xAxis.length; i++) {
          let list = [];
          for (let j = 0; j < line_obj_i_want_to_customize_it.value.names.length; j++) {
            data[v2] = line_obj_i_want_to_customize_it.value.xAxis[i];
            data[v1] = line_obj_i_want_to_customize_it.value.names[j];
            await $get("/api/i_want_to_customize_it/sum", data).then((json) => {
              if (json.result) {
                list[j] = json.result;
              } else {
                list[j] = 0;
              }
            });
          }
          line_obj_i_want_to_customize_it.value.values.push(list);
        }
        if (names_flag) {
          get_nickname(line_obj_i_want_to_customize_it.value.names, true);
        }
        if (xAxis_flag) {
          get_nickname(line_obj_i_want_to_customize_it.value.xAxis, true);
        }
                                                                                  };
                        onMounted(() => {
    getMonthDateList();
    // 获取用户状态
    get_list_users_state();
    // 商品销售数量统计
    get_order_month_some_price(null, bar_obj_shop_num.value);
    //总销售金额统计
    get_order_month_some_price(null, line_obj_shop_money.value);
    //试卷平均分统计
    get_url_subject_list();
    // 获取用户总数1-6月
    get_list_users_sums();
    // 总访问数1-6月
    get_list_hits_sums();
    // 收藏数统计1-6月
    get_list_collect_sums();
    // 点赞数	1-6月
    get_list_praise_sums();
    // 评论数	1-6月
    get_list_comments_sums();
    // 用户状态--散点图  1-6月
    get_bubble_user_status()
    // 数据预览模块
    get_list_count()
      // 执行注册用户数据获取
    get_list_registered_user();
        // 执行商家用户数据获取
    get_list_merchant_users();
            // 执行定制商品数据获取
    get_list_customized_products();
        // 执行我要定制数据获取
    get_list_i_want_to_customize_it();
              });
</script>
<style lang="less" scoped>
  .chart {
    display: block;
    width: 100%;
    height: 620px;
    padding: 1rem;
    position: relative;
  }

  .statistics {
    width: 100%;
    height: 240px;
    overflow-y: auto;

    .sumList {
      text-align: center;
      font-size: 12px;
      color: gray;
      border-radius: 8px;
      padding: 5px;
      border: 1px solid gainsboro;
    }
  }

  .info {
    display: block;
    width: 100%;
    height: 240px;
    padding: 1rem;
    position: relative;

    .UserInfo {
      p {
        line-height: 30px;
      }

      img {
        width: 100px;
        height: 100px;
      }

      .logotime {
        text-align: center;
        font-size: 14px;
        line-height: 30px;
        border-top: 1px #d9d9d9 solid;
        margin: 10px 0;
      }
    }
  }

  .chartsHeiht {
    margin-top: 20px;
    height: 500px;
  }

  .el-col {
    padding: 0.5rem;
  }

  .card {
    overflow: hidden;
  }

  .iframe_box,
  .iframe_box_change {
    width: 100%;
    height: 1180px;
    position: relative;
    margin-top: 25px;
  }

  .iframe_box_change {
    height: 580px;
    padding-top: 50px;
  }

  .iframe_box .iframe_box_content,
  .iframe_box_change .iframe_box_content {
    width: 100%;
    height: 100%;
  }

  .iframe_box_top {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100px;
    font-size: 25px;
    line-height: 100px;
    background: #fff;
    z-index: 99999999;
    padding-left: 50px;
  }

  #iframe_box_face div::before {
    content: "";
    width: 100px;
    position: absolute;
    top: 154px;
    right: 129px;
    z-index: 999;
    height: 20px;
    background-color: #ffffff;
  }

  #iframe_box_face > h1 {
    margin-top: 100px;
    margin-bottom: 20px;
  }

  #outerdiv {
    margin: 0 auto;
    width: 1500px;
    height: 600px;
    overflow: hidden;
    position: relative;
  }

  #inneriframe {
    position: absolute;
    top: -150px;
    left: 0px;
    width: 1300px;
    height: 450px;
  }
</style>
